home *** CD-ROM | disk | FTP | other *** search
/ User's Choice Windows CD / User's Choice Windows CD (CMS Software)(1993).iso / utility1 / gs261src.zip / GDEVXINI.C < prev    next >
C/C++ Source or Header  |  1993-05-28  |  31KB  |  916 lines

  1. /* Copyright (C) 1989, 1992, 1993 Aladdin Enterprises.  All rights reserved.
  2.  
  3. This file is part of Ghostscript.
  4.  
  5. Ghostscript is distributed in the hope that it will be useful, but
  6. WITHOUT ANY WARRANTY.  No author or distributor accepts responsibility
  7. to anyone for the consequences of using it or for whether it serves any
  8. particular purpose or works at all, unless he says so in writing.  Refer
  9. to the Ghostscript General Public License for full details.
  10.  
  11. Everyone is granted permission to copy, modify and redistribute
  12. Ghostscript, but only under the conditions described in the Ghostscript
  13. General Public License.  A copy of this license is supposed to have been
  14. given to you along with Ghostscript so you can know your rights and
  15. responsibilities.  It should be in a file named COPYING.  Among other
  16. things, the copyright notice and this notice must be preserved on all
  17. copies.  */
  18.  
  19. /* gdevxini.c */
  20. /* X Windows driver initialization for Ghostscript library */
  21. #include "gx.h"            /* for gx_bitmap; includes std.h */
  22. #include "memory_.h"
  23. #include "math_.h"
  24. #include "x_.h"
  25. #include "gxdevice.h"
  26. #include "gdevx.h"
  27.  
  28. extern char *getenv(P1(const char *));
  29.  
  30. private XtResource resources[] = {
  31.     {XtNbackground, XtCBackground, XtRPixel, sizeof(Pixel),
  32.      XtOffsetOf(gx_device_X, background),
  33.      XtRString, (XtPointer)"XtDefaultBackground"},
  34.     {XtNborderColor, XtCBorderColor, XtRPixel, sizeof(Pixel),
  35.      XtOffsetOf(gx_device_X, borderColor),
  36.      XtRString, (XtPointer)"XtDefaultForeground"},
  37.     {XtNborderWidth, XtCBorderWidth, XtRDimension, sizeof(Dimension),
  38.      XtOffsetOf(gx_device_X, borderWidth),
  39.      XtRImmediate, (XtPointer)1},
  40.     {"dingbatFonts", "DingbatFonts", XtRString, sizeof(String), 
  41.      XtOffsetOf(gx_device_X, dingbatFonts),
  42.      XtRString, "ZapfDingbats: -Adobe-ITC Zapf Dingbats-Medium-R-Normal--"},
  43.     {"externalFontTolerance", "ExternalFontTolerance", XtRFloat, sizeof(float),
  44.      XtOffsetOf(gx_device_X, xFontTolerance),
  45.      XtRString, (XtPointer)"10.0"},
  46.     {XtNforeground, XtCForeground, XtRPixel, sizeof(Pixel),
  47.      XtOffsetOf(gx_device_X, foreground),
  48.      XtRString, (XtPointer)"XtDefaultForeground"},
  49.     {XtNgeometry, XtCGeometry, XtRString, sizeof(String), 
  50.      XtOffsetOf(gx_device_X, geometry),
  51.      XtRString, NULL},
  52.     {"logExternalFonts", "LogExternalFonts", XtRBoolean, sizeof(Boolean), 
  53.      XtOffsetOf(gx_device_X, logXFonts),
  54.      XtRImmediate, (XtPointer)False},
  55.     {"maxGrayRamp", "MaxGrayRamp", XtRInt, sizeof(int), 
  56.      XtOffsetOf(gx_device_X, maxGrayRamp),
  57.      XtRImmediate, (XtPointer)128},
  58.     {"maxRGBRamp", "MaxRGBRamp", XtRInt, sizeof(int), 
  59.      XtOffsetOf(gx_device_X, maxRGBRamp),
  60.      XtRImmediate, (XtPointer)5},
  61.     {"palette", "Palette", XtRString, sizeof(String), 
  62.      XtOffsetOf(gx_device_X, palette),
  63.      XtRString, "Color"},
  64.  
  65.     /* I had to compress the whitespace out of the default string to
  66.      * satisfy certain balky compilers.
  67.      */
  68.     {"regularFonts", "RegularFonts", XtRString, sizeof(String), 
  69.      XtOffsetOf(gx_device_X, regularFonts),
  70.      XtRString, "\
  71. AvantGarde-Book:-Adobe-ITC Avant Garde Gothic-Book-R-Normal--\n\
  72. AvantGarde-BookOblique:-Adobe-ITC Avant Garde Gothic-Book-O-Normal--\n\
  73. AvantGarde-Demi:-Adobe-ITC Avant Garde Gothic-Demi-R-Normal--\n\
  74. AvantGarde-DemiOblique:-Adobe-ITC Avant Garde Gothic-Demi-O-Normal--\n\
  75. Bookman-Demi:-Adobe-ITC Bookman-Demi-R-Normal--\n\
  76. Bookman-DemiItalic:-Adobe-ITC Bookman-Demi-I-Normal--\n\
  77. Bookman-Light:-Adobe-ITC Bookman-Light-R-Normal--\n\
  78. Bookman-LightItalic:-Adobe-ITC Bookman-Light-I-Normal--\n\
  79. Courier:-Adobe-Courier-Medium-R-Normal--\n\
  80. Courier-Bold:-Adobe-Courier-Bold-R-Normal--\n\
  81. Courier-BoldOblique:-Adobe-Courier-Bold-O-Normal--\n\
  82. Courier-Oblique:-Adobe-Courier-Medium-O-Normal--\n\
  83. Helvetica:-Adobe-Helvetica-Medium-R-Normal--\n\
  84. Helvetica-Bold:-Adobe-Helvetica-Bold-R-Normal--\n\
  85. Helvetica-BoldOblique:-Adobe-Helvetica-Bold-O-Normal--\n\
  86. Helvetica-Narrow:-Adobe-Helvetica-Medium-R-Narrow--\n\
  87. Helvetica-Narrow-Bold:-Adobe-Helvetica-Bold-R-Narrow--\n\
  88. Helvetica-Narrow-BoldOblique:-Adobe-Helvetica-Bold-O-Narrow--\n\
  89. Helvetica-Narrow-Oblique:-Adobe-Helvetica-Medium-O-Narrow--\n\
  90. Helvetica-Oblique:-Adobe-Helvetica-Medium-O-Normal--\n\
  91. NewCenturySchlbk-Bold:-Adobe-New Century Schoolbook-Bold-R-Normal--\n\
  92. NewCenturySchlbk-BoldItalic:-Adobe-New Century Schoolbook-Bold-I-Normal--\n\
  93. NewCenturySchlbk-Italic:-Adobe-New Century Schoolbook-Medium-I-Normal--\n\
  94. NewCenturySchlbk-Roman:-Adobe-New Century Schoolbook-Medium-R-Normal--\n\
  95. Palatino-Bold:-Adobe-Palatino-Bold-R-Normal--\n\
  96. Palatino-BoldItalic:-Adobe-Palatino-Bold-I-Normal--\n\
  97. Palatino-Italic:-Adobe-Palatino-Medium-I-Normal--\n\
  98. Palatino-Roman:-Adobe-Palatino-Medium-R-Normal--\n\
  99. Times-Bold:-Adobe-Times-Bold-R-Normal--\n\
  100. Times-BoldItalic:-Adobe-Times-Bold-I-Normal--\n\
  101. Times-Italic:-Adobe-Times-Medium-I-Normal--\n\
  102. Times-Roman:-Adobe-Times-Medium-R-Normal--\n\
  103. ZapfChancery-MediumItalic:-Adobe-ITC Zapf Chancery-Medium-I-Normal--"},
  104.     {"symbolFonts", "SymbolFonts", XtRString, sizeof(String), 
  105.      XtOffsetOf(gx_device_X, symbolFonts),
  106.      XtRString, "Symbol: -Adobe-Symbol-Medium-R-Normal--"},
  107.     {"useBackingPixmap", "UseBackingPixmap", XtRBoolean, sizeof(Boolean), 
  108.      XtOffsetOf(gx_device_X, useBackingPixmap),
  109.      XtRImmediate, (XtPointer)True},
  110.     {"useExternalFonts", "UseExternalFonts", XtRBoolean, sizeof(Boolean), 
  111.      XtOffsetOf(gx_device_X, useXFonts),
  112.      XtRImmediate, (XtPointer)True},
  113.     {"useScalableFonts", "UseScalableFonts", XtRBoolean, sizeof(Boolean), 
  114.      XtOffsetOf(gx_device_X, useScalableFonts),
  115.      XtRImmediate, (XtPointer)True},
  116.     {"useXPutImage", "UseXPutImage", XtRBoolean, sizeof(Boolean), 
  117.      XtOffsetOf(gx_device_X, useXPutImage),
  118.      XtRImmediate, (XtPointer)True},
  119.     {"useXSetTile", "UseXSetTile", XtRBoolean, sizeof(Boolean), 
  120.      XtOffsetOf(gx_device_X, useXSetTile),
  121.      XtRImmediate, (XtPointer)True},
  122.     {"xResolution", "Resolution", XtRFloat, sizeof(float),
  123.      XtOffsetOf(gx_device_X, xResolution),
  124.      XtRString, (XtPointer)"0.0"},
  125.     {"yResolution", "Resolution", XtRFloat, sizeof(float),
  126.      XtOffsetOf(gx_device_X, yResolution),
  127.      XtRString, (XtPointer)"0.0"},
  128. };
  129.  
  130. /* Define constants for orientation from ghostview */
  131. /* Number represents clockwise rotation of the paper in degrees */
  132. typedef enum {
  133.   Portrait = 0,        /* Normal portrait orientation */
  134.   Landscape = 90,    /* Normal landscape orientation */
  135.   Upsidedown = 180,    /* Don't think this will be used much */
  136.   Seascape = 270    /* Landscape rotated the wrong way */
  137. } orientation;
  138.  
  139. /* Forward references */
  140. private void gdev_x_setup_colors(P1(gx_device_X *));
  141. private void gdev_x_setup_fontmap(P1(gx_device_X *));
  142.  
  143. /* Open the X device */
  144. int
  145. gdev_x_open(register gx_device_X *xdev)
  146. {
  147.     XSizeHints sizehints;
  148.     char *window_id;
  149.     XEvent event;
  150.     XVisualInfo xvinfo;
  151.     int nitems;
  152.     XtAppContext app_con;
  153.     Widget toplevel;
  154.     Display *dpy;
  155.     int zero = 0;
  156.  
  157. #ifdef DEBUG
  158.     if (gs_debug['X']) {
  159.     extern int _Xdebug;
  160.  
  161.     _Xdebug = 1;
  162.     }
  163. #endif
  164.     if (!(xdev->dpy = XOpenDisplay((char *)NULL))) {
  165.     char *dispname = getenv("DISPLAY");
  166.  
  167.     eprintf1("gs: Cannot open X display `%s'.\n",
  168.          (dispname == NULL ? "(null)" : dispname));
  169.     exit(1);
  170.     }
  171.     xdev->dest = 0;
  172.     if ((window_id = getenv("GHOSTVIEW"))) {
  173.     if (!(xdev->ghostview = sscanf(window_id, "%d %d",
  174.                        &(xdev->win), &(xdev->dest)))) {
  175.         eprintf("gs: Cannot get Window ID from ghostview.\n");
  176.         exit(1);
  177.     }
  178.     }
  179.     if (xdev->ghostview) {
  180.     XWindowAttributes attrib;
  181.     Atom type;
  182.     int format;
  183.     unsigned long nitems, bytes_after;
  184.     char *buf;
  185.     Atom ghostview_atom = XInternAtom(xdev->dpy, "GHOSTVIEW", False);
  186.  
  187.     if (XGetWindowAttributes(xdev->dpy, xdev->win, &attrib)) {
  188.         xdev->scr = attrib.screen;
  189.         xvinfo.visual = attrib.visual;
  190.         xdev->cmap = attrib.colormap;
  191.         xdev->width = attrib.width;
  192.         xdev->height = attrib.height;
  193.     }
  194.     /* Delete property if explicit dest is given */
  195.     if (XGetWindowProperty(xdev->dpy, xdev->win, ghostview_atom, 0,
  196.                    256, (xdev->dest != 0), XA_STRING,
  197.                    &type, &format, &nitems, &bytes_after,
  198.                    (unsigned char **)&buf) == 0 &&
  199.         type == XA_STRING) {
  200.         int llx, lly, urx, ury;
  201.         int left_margin = 0, bottom_margin = 0;
  202.         int right_margin = 0, top_margin = 0;
  203.  
  204.         /* We declare page_orientation as an int so that we can */
  205.         /* use an int * to reference it for sscanf; compilers */
  206.         /* might be tempted to use less space to hold it if */
  207.         /* it were declared as an orientation. */
  208.         int /*orientation*/ page_orientation;
  209.         float xppp, yppp;    /* pixels per point */
  210.         nitems = sscanf(buf,
  211.                 "%d %d %d %d %d %d %f %f %d %d %d %d",
  212.                 &(xdev->bpixmap), &page_orientation,
  213.                 &llx, &lly, &urx, &ury,
  214.                 &(xdev->x_pixels_per_inch),
  215.                 &(xdev->y_pixels_per_inch),
  216.                 &left_margin, &bottom_margin,
  217.                 &right_margin, &top_margin);
  218.         if (!(nitems == 8 || nitems == 12)) {
  219.         eprintf("gs: Cannot get ghostview property.\n");
  220.         exit(1);
  221.         }
  222.         if (xdev->dest && xdev->bpixmap) {
  223.         eprintf("gs: Both destination and backing pixmap specified.\n");
  224.         exit(1);
  225.         }
  226.         if (xdev->dest) {
  227.         Window root;
  228.         int x, y;
  229.         unsigned int width, height;
  230.         unsigned int border_width, depth;
  231.  
  232.         if (XGetGeometry(xdev->dpy, xdev->dest, &root, &x, &y,
  233.                  &width, &height, &border_width, &depth)) {
  234.             xdev->width = width;
  235.             xdev->height = height;
  236.         }
  237.         }
  238.         xppp = xdev->x_pixels_per_inch / 72.0;
  239.         yppp = xdev->y_pixels_per_inch / 72.0;
  240.         switch (page_orientation) {
  241.         case Portrait:
  242.         xdev->initial_matrix.xx = xppp;
  243.         xdev->initial_matrix.xy = 0.0;
  244.         xdev->initial_matrix.yx = 0.0;
  245.         xdev->initial_matrix.yy = -yppp;
  246.         xdev->initial_matrix.tx = -llx * xppp;
  247.         xdev->initial_matrix.ty = ury * yppp;
  248.         break;
  249.         case Landscape:
  250.         xdev->initial_matrix.xx = 0.0;
  251.         xdev->initial_matrix.xy = yppp;
  252.         xdev->initial_matrix.yx = xppp;
  253.         xdev->initial_matrix.yy = 0.0;
  254.         xdev->initial_matrix.tx = -lly * xppp;
  255.         xdev->initial_matrix.ty = -llx * yppp;
  256.         break;
  257.         case Upsidedown:
  258.         xdev->initial_matrix.xx = -xppp;
  259.         xdev->initial_matrix.xy = 0.0;
  260.         xdev->initial_matrix.yx = 0.0;
  261.         xdev->initial_matrix.yy = yppp;
  262.         xdev->initial_matrix.tx = urx * xppp;
  263.         xdev->initial_matrix.ty = -lly * yppp;
  264.         break;
  265.         case Seascape:
  266.         xdev->initial_matrix.xx = 0.0;
  267.         xdev->initial_matrix.xy = -yppp;
  268.         xdev->initial_matrix.yx = -xppp;
  269.         xdev->initial_matrix.yy = 0.0;
  270.         xdev->initial_matrix.tx = ury * xppp;
  271.         xdev->initial_matrix.ty = urx * yppp;
  272.         break;
  273.         }
  274.  
  275.         /* The following sets the imageable area according to the */
  276.         /* bounding box and margins sent by ghostview.            */
  277.         xdev->l_margin = (llx - left_margin) / 72.0;
  278.         xdev->b_margin = (lly - bottom_margin) / 72.0;
  279.         xdev->r_margin = xdev->width / xdev->x_pixels_per_inch -
  280.                  (urx + right_margin) / 72.0;
  281.         xdev->t_margin = xdev->height / xdev->y_pixels_per_inch -
  282.                  (ury + top_margin) / 72.0;
  283.     } else {
  284.         eprintf("gs: Cannot get ghostview property.\n");
  285.         exit(1);
  286.     }
  287.     } else {
  288.     Screen *scr = DefaultScreenOfDisplay(xdev->dpy);
  289.  
  290.     xdev->scr = scr;
  291.     xvinfo.visual = DefaultVisualOfScreen(scr);
  292.     xdev->cmap = DefaultColormapOfScreen(scr);
  293.     }
  294.  
  295.     xvinfo.visualid = XVisualIDFromVisual(xvinfo.visual);
  296.     xdev->vinfo = XGetVisualInfo(xdev->dpy, VisualIDMask, &xvinfo, &nitems);
  297.     if (xdev->vinfo == NULL) {
  298.     eprintf("gs: Cannot get XVisualInfo.\n");
  299.     exit(1);
  300.     }
  301.     /* Get X Resources.  Use the toolkit for this. */
  302.     XtToolkitInitialize();
  303.     app_con = XtCreateApplicationContext();
  304.     dpy = XtOpenDisplay(app_con, NULL, "ghostscript", "Ghostscript",
  305.             NULL, 0, &zero, NULL);
  306.     toplevel = XtAppCreateShell(NULL, "Ghostscript",
  307.                 applicationShellWidgetClass, dpy, NULL, 0);
  308.     XtGetApplicationResources(toplevel, (XtPointer) xdev,
  309.                   resources, XtNumber(resources), NULL, 0);
  310.     XtDestroyWidget(toplevel);
  311.     XtCloseDisplay(dpy);
  312.     XtDestroyApplicationContext(app_con);
  313.  
  314.     gdev_x_setup_colors(xdev);
  315.     gdev_x_setup_fontmap(xdev);
  316.  
  317.     if (!xdev->ghostview) {
  318.     XWMHints wm_hints;
  319.     XSetWindowAttributes xswa;
  320.     gx_device *dev = (gx_device *)xdev;
  321.  
  322.     /* Take care of resolution and paper size. */
  323.     if (xdev->x_pixels_per_inch == FAKE_RES ||
  324.         xdev->y_pixels_per_inch == FAKE_RES) {
  325.         float xsize, ysize;
  326.  
  327.         xsize = (float)xdev->width / xdev->x_pixels_per_inch;
  328.         ysize = (float)xdev->height / xdev->y_pixels_per_inch;
  329.  
  330.         if (xdev->xResolution == 0.0 && xdev->yResolution == 0.0) {
  331.         float dpi, xdpi, ydpi;
  332.  
  333.         xdpi = 25.4 * WidthOfScreen(xdev->scr) /
  334.                WidthMMOfScreen(xdev->scr);
  335.         ydpi = 25.4 * HeightOfScreen(xdev->scr) /
  336.                HeightMMOfScreen(xdev->scr);
  337.         dpi = min(xdpi, ydpi);
  338.  
  339.         while (xsize*dpi > WidthOfScreen(xdev->scr)-32 ||
  340.                ysize*dpi > HeightOfScreen(xdev->scr)-32) {
  341.             dpi *= 0.95;
  342.         }
  343.         xdev->x_pixels_per_inch = dpi;
  344.         xdev->y_pixels_per_inch = dpi;
  345.         } else {
  346.         xdev->x_pixels_per_inch = xdev->xResolution;
  347.         xdev->y_pixels_per_inch = xdev->yResolution;
  348.         }
  349.         if (xdev->width > WidthOfScreen(xdev->scr)) {
  350.         xdev->width = xsize*xdev->x_pixels_per_inch;
  351.         }
  352.         if (xdev->height > HeightOfScreen(xdev->scr)) {
  353.         xdev->height = ysize*xdev->y_pixels_per_inch;
  354.         }
  355.     }
  356.  
  357.     sizehints.x = 0;
  358.     sizehints.y = 0;
  359.     sizehints.width = xdev->width;
  360.     sizehints.height = xdev->height;
  361.     sizehints.flags = 0;
  362.  
  363.     if (xdev->geometry != NULL) {
  364.         /*
  365.          * Note that border_width must be set first.  We can't use
  366.          * scr, because that is a Screen*, and XWMGeometry wants
  367.          * the screen number.
  368.          */
  369.         char gstr[40];
  370.         int bitmask;
  371.  
  372.         sprintf(gstr, "%dx%d+%d+%d", sizehints.width,
  373.             sizehints.height, sizehints.x, sizehints.y);
  374.         bitmask = XWMGeometry(xdev->dpy, DefaultScreen(xdev->dpy),
  375.                   xdev->geometry, gstr, xdev->borderWidth,
  376.                   &sizehints,
  377.                   &sizehints.x, &sizehints.y,
  378.                   &sizehints.width, &sizehints.height,
  379.                   &sizehints.win_gravity);
  380.  
  381.         if (bitmask & (XValue | YValue))
  382.         sizehints.flags |= USPosition;
  383.     }
  384.  
  385.     gx_default_get_initial_matrix(dev, &(xdev->initial_matrix));
  386.  
  387.     xswa.event_mask = ExposureMask;
  388.     xswa.background_pixel = xdev->background;
  389.     xswa.border_pixel = xdev->borderColor;
  390.     xswa.colormap = xdev->cmap;
  391.     xdev->win = XCreateWindow(xdev->dpy, RootWindowOfScreen(xdev->scr),
  392.                   sizehints.x, sizehints.y,    /* upper left */
  393.                   xdev->width, xdev->height,
  394.                   xdev->borderWidth,
  395.                   xdev->vinfo->depth,
  396.                   InputOutput,    /* class */
  397.                   xdev->vinfo->visual,    /* visual */
  398.                   CWEventMask | CWBackPixel |
  399.                   CWBorderPixel | CWColormap,
  400.                   &xswa);
  401.     XStoreName(xdev->dpy, xdev->win, "ghostscript");
  402.     XSetWMNormalHints(xdev->dpy, xdev->win, &sizehints);
  403.     wm_hints.flags = InputHint;
  404.     wm_hints.input = False;
  405.     XSetWMHints(xdev->dpy, xdev->win, &wm_hints); /* avoid input focus */
  406.     }
  407.  
  408.     xdev->ht.pixmap = (Pixmap) 0;
  409.     xdev->ht.id = gx_no_bitmap_id;;
  410.     xdev->fill_style = FillSolid;
  411.     xdev->function = GXcopy;
  412.     xdev->fid = (Font) 0;
  413.  
  414.     /* Set up a graphics context */
  415.     xdev->gc = XCreateGC(xdev->dpy, xdev->win, 0, (XGCValues *) NULL);
  416.     XSetFunction(xdev->dpy, xdev->gc, GXcopy);
  417.     XSetLineAttributes(xdev->dpy, xdev->gc, 0,
  418.                LineSolid, CapButt, JoinMiter);
  419.  
  420.     gdev_x_clear_window(xdev);
  421.  
  422.     if (!xdev->ghostview) {    /* Make the window appear. */
  423.     XMapWindow(xdev->dpy, xdev->win);
  424.  
  425.     /* Before anything else, do a flush and wait for */
  426.     /* an exposure event. */
  427.     XFlush(xdev->dpy);
  428.     XNextEvent(xdev->dpy, &event);
  429.     } else {
  430.     /* Create an unmapped window, that the window manager will ignore.
  431.      * This invisible window will be used to receive "next page"
  432.      * events from ghostview */
  433.     XSetWindowAttributes attributes;
  434.  
  435.     attributes.override_redirect = True;
  436.     xdev->mwin = XCreateWindow(xdev->dpy, RootWindowOfScreen(xdev->scr),
  437.                    0, 0, 1, 1, 0, CopyFromParent,
  438.                    CopyFromParent, CopyFromParent,
  439.                    CWOverrideRedirect, &attributes);
  440.     xdev->next = XInternAtom(xdev->dpy, "NEXT", False);
  441.     xdev->page = XInternAtom(xdev->dpy, "PAGE", False);
  442.     xdev->done = XInternAtom(xdev->dpy, "DONE", False);
  443.     }
  444.  
  445.     xdev->ht.no_pixmap = XCreatePixmap(xdev->dpy, xdev->win, 1, 1,
  446.                        xdev->vinfo->depth);
  447.  
  448.     XSync(xdev->dpy, 0);
  449.     return 0;
  450. }
  451.  
  452. /* Catch the alloc error when there is not enough resources for the
  453.  * backing pixmap.  Automatically shut off backing pixmap and let the
  454.  * user know when this happens.
  455.  */
  456. private Boolean alloc_error;
  457. private XErrorHandler oldhandler;
  458.  
  459. private int
  460. x_catch_alloc(Display *dpy, XErrorEvent *err)
  461. {
  462.     if (err->error_code == BadAlloc)
  463.     alloc_error = True;
  464.     if (alloc_error)
  465.     return 0;
  466.     oldhandler(dpy, err);
  467. }
  468.  
  469. /* Allocate the backing pixmap, if any, and clear the window. */
  470. void
  471. gdev_x_clear_window(gx_device_X *xdev)
  472. {
  473.     if (!xdev->ghostview) {
  474.     if (xdev->useBackingPixmap) {
  475.         oldhandler = XSetErrorHandler(x_catch_alloc);
  476.         alloc_error = False;
  477.         xdev->bpixmap =
  478.         XCreatePixmap(xdev->dpy, xdev->win,
  479.                   xdev->width, xdev->height,
  480.                   xdev->vinfo->depth);
  481.         XSync(xdev->dpy, False);    /* Force the error */
  482.         if (alloc_error) {
  483.         xdev->useBackingPixmap = False;
  484.         eprintf("Warning: Failed to allocated backing pixmap.\n");
  485.         if (xdev->bpixmap) {
  486.             XFreePixmap(xdev->dpy, xdev->bpixmap);
  487.             xdev->bpixmap = None;
  488.             XSync(xdev->dpy, False);    /* Force the error */
  489.         }
  490.         }
  491.         oldhandler = XSetErrorHandler(oldhandler);
  492.     } else
  493.         xdev->bpixmap = (Pixmap) 0;
  494.     }
  495.     /* Clear the destination pixmap to avoid initializing with garbage. */
  496.     if (xdev->dest != (Pixmap) 0) {
  497.     XSetForeground(xdev->dpy, xdev->gc, xdev->background);
  498.     XFillRectangle(xdev->dpy, xdev->dest, xdev->gc,
  499.                0, 0, xdev->width, xdev->height);
  500.     } else {
  501.     xdev->dest = (xdev->bpixmap != (Pixmap) 0 ?
  502.               xdev->bpixmap : (Pixmap) xdev->win);
  503.     }
  504.  
  505.     /* Clear the background pixmap to avoid initializing with garbage. */
  506.     if (xdev->bpixmap != (Pixmap) 0) {
  507.     if (!xdev->ghostview)
  508.         XSetWindowBackgroundPixmap(xdev->dpy, xdev->win, xdev->bpixmap);
  509.     XSetForeground(xdev->dpy, xdev->gc, xdev->background);
  510.     XFillRectangle(xdev->dpy, xdev->bpixmap, xdev->gc,
  511.                0, 0, xdev->width, xdev->height);
  512.     }
  513.     /* Initialize foreground and background colors */
  514.     xdev->back_color = xdev->background;
  515.     XSetBackground(xdev->dpy, xdev->gc, xdev->background);
  516.     xdev->fore_color = xdev->background;
  517.     XSetForeground(xdev->dpy, xdev->gc, xdev->background);
  518.     xdev->colors_or = xdev->colors_and = xdev->background;
  519. }
  520.  
  521. #if HaveStdCMap
  522. /* get Standard colormap if available */
  523. private XStandardColormap *
  524. x_get_std_cmap(gx_device_X *xdev, Atom prop)
  525. {
  526.     int i;
  527.     XStandardColormap *scmap, *sp;
  528.     int nitems;
  529.  
  530.     if (XGetRGBColormaps(xdev->dpy, RootWindowOfScreen(xdev->scr),
  531.              &scmap, &nitems, prop))
  532.     for (i = 0, sp = scmap; i < nitems; i++, sp++)
  533.         if (xdev->cmap == sp->colormap)
  534.         return sp;
  535.  
  536.     return NULL;
  537. }
  538. #endif
  539.  
  540. /* Setup color mapping. */
  541. private void
  542. gdev_x_setup_colors(gx_device_X *xdev)
  543. {
  544.     char palette;
  545.  
  546.     palette = ((xdev->vinfo->class != StaticGray) &&
  547.            (xdev->vinfo->class != GrayScale) ? 'C' :  /* Color */
  548.            (xdev->vinfo->colormap_size > 2) ?  'G' :  /* GrayScale */
  549.                            'M');  /* MonoChrome */
  550.     if (xdev->ghostview) {
  551.     Atom gv_colors = XInternAtom(xdev->dpy, "GHOSTVIEW_COLORS", False);
  552.     Atom type;
  553.     int format;
  554.     unsigned long nitems, bytes_after;
  555.     char *buf;
  556.  
  557.     /* Delete property if explicit dest is given */
  558.     if (XGetWindowProperty(xdev->dpy, xdev->win, gv_colors, 0,
  559.                    256, (xdev->dest != 0), XA_STRING,
  560.                    &type, &format, &nitems, &bytes_after,
  561.                    (unsigned char **)&buf) == 0 &&
  562.         type == XA_STRING) {
  563.         nitems = sscanf(buf, "%*s %d %d", &(xdev->foreground),
  564.                               &(xdev->background));
  565.         if (nitems != 2 || *buf != 'M' || *buf != 'G' || *buf != 'C') {
  566.         eprintf("gs: Malformed ghostview color property.\n");
  567.         exit(1);
  568.         }
  569.         palette = max(palette, *buf);
  570.     }
  571.     } else {
  572.     if      (xdev->palette[0] == 'c') xdev->palette[0] = 'C';
  573.     else if (xdev->palette[0] == 'g') xdev->palette[0] = 'G';
  574.     else if (xdev->palette[0] == 'm') xdev->palette[0] = 'M';
  575.     palette = max(palette, xdev->palette[0]);
  576.     }
  577.  
  578.     /* set up color mappings here */
  579.     xdev->color_mask = 0xffff - (0xffff >> xdev->vinfo->bits_per_rgb);
  580.     xdev->half_dev_color = 1 << (15 - xdev->vinfo->bits_per_rgb);
  581. #define num_rgb (1 << xdev->vinfo->bits_per_rgb)
  582.  
  583. #if HaveStdCMap
  584.     xdev->std_cmap = NULL;
  585. #endif
  586.     xdev->dither_colors = NULL;
  587.     xdev->dynamic_colors = NULL;
  588.     xdev->color_info.depth = xdev->vinfo->depth;
  589.  
  590.     if (palette == 'C') {
  591.     xdev->color_info.num_components = 3;
  592.     xdev->color_info.max_gray =
  593.         xdev->color_info.max_rgb = num_rgb - 1;
  594.     xdev->dither_colors = NULL;
  595. #if HaveStdCMap
  596.     /* Get a standard color map if available */
  597.     if (xdev->vinfo->visual == DefaultVisualOfScreen(xdev->scr)) {
  598.         xdev->std_cmap = x_get_std_cmap(xdev, XA_RGB_DEFAULT_MAP);
  599.     } else {
  600.         xdev->std_cmap = x_get_std_cmap(xdev, XA_RGB_BEST_MAP);
  601.     }
  602.     if (xdev->std_cmap) {
  603.         xdev->color_info.dither_gray =
  604.         xdev->color_info.dither_rgb =
  605.         min(xdev->std_cmap->red_max,
  606.             min(xdev->std_cmap->green_max,
  607.             xdev->std_cmap->blue_max)) + 1;
  608.     } else
  609. #endif
  610.     /* Otherwise set up a rgb cube of our own */
  611.     /* The color cube is limited to about 1/2 of the available */
  612.     /* colormap, the user specified maxRGBRamp (usually 5), */
  613.     /* or the number of representable colors */
  614. #define cube(r) (r*r*r)
  615. #define cbrt(r) pow(r, 1.0/3.0)
  616.     {
  617.         int avail_colors = xdev->vinfo->colormap_size;
  618.  
  619.         while (!xdev->dither_colors && avail_colors) {
  620.         int ramp_size = min((int)cbrt((double)avail_colors / 2.0),
  621.                     min(xdev->maxRGBRamp, num_rgb));
  622.         int max_rgb = ramp_size - 1;
  623.         int r, g, b;
  624.  
  625.         if (ramp_size < 2) {
  626.             avail_colors = 0;
  627.             goto no_cube;
  628.         }
  629.         xdev->color_info.dither_gray =
  630.             xdev->color_info.dither_rgb = ramp_size;
  631.         xdev->dither_colors =
  632.             (x_pixel *) gs_malloc(sizeof(x_pixel), cube(ramp_size),
  633.                       "gdev_x_rgb_cube");
  634.         for (r = 0; r < ramp_size; r++) {
  635.             for (g = 0; g < ramp_size; g++) {
  636.             for (b = 0; b < ramp_size; b++) {
  637.                 if (r == 0 && g == 0 && b == 0) {
  638.                 xdev->dither_colors[0] = xdev->foreground;
  639.                 } else if (r == max_rgb && g == max_rgb &&
  640.                        b == max_rgb) {
  641.                 xdev->dither_colors[cube_index(r, g, b)] =
  642.                     xdev->background;
  643.                 } else {
  644.                 XColor xc;
  645.  
  646.                 xc.red = (0xffff * r / max_rgb) &
  647.                      xdev->color_mask;
  648.                 xc.green = (0xffff * g / max_rgb) &
  649.                      xdev->color_mask;
  650.                 xc.blue = (0xffff * b / max_rgb) &
  651.                      xdev->color_mask;
  652.                 if (XAllocColor(xdev->dpy, xdev->cmap, &xc)) {
  653.                     xdev->dither_colors[cube_index(r, g, b)] =
  654.                     xc.pixel;
  655.                 } else {
  656.                     int i;
  657.  
  658.                     avail_colors = cube_index(r, g, b) - 1;
  659.                     for (i = 1; i <= avail_colors; i++) {
  660.                     XFreeColors(xdev->dpy, xdev->cmap,
  661.                             &(xdev->dither_colors[i]),
  662.                             1, 0);
  663.                     }
  664.                     gs_free((char *)xdev->dither_colors,
  665.                         sizeof(x_pixel), cube(ramp_size),
  666.                         "gdev_x_rgb_cube");
  667.                     xdev->dither_colors = NULL;
  668.                     goto no_cube;
  669.                 }
  670.                 }
  671.             }
  672.             }
  673.         }
  674. no_cube:    ;
  675.         }
  676.  
  677.         if (!xdev->dither_colors) {
  678.         goto grayscale;
  679.         }
  680.     }
  681.  
  682.     /* Allocate space for dynamic colors, do at most 256 */
  683.     /* If there are more avaiaible, we ask the X server */
  684.     xdev->dynamic_number = 0;
  685.     xdev->dynamic_size = min(256, xdev->vinfo->colormap_size);
  686.     xdev->dynamic_size -= cube(xdev->color_info.dither_rgb);
  687.     if (xdev->dynamic_size) {
  688.         xdev->dynamic_colors =
  689.         (XColor *) gs_malloc(sizeof(XColor), xdev->dynamic_size,
  690.                      "gdev_x_dynamic_colors");
  691.     } else {
  692.         xdev->dynamic_colors = NULL;
  693.     }
  694. #undef cube
  695.     } else if (palette == 'G') {
  696. grayscale:
  697.     xdev->color_info.num_components = 1;
  698.     xdev->color_info.max_gray = num_rgb - 1;
  699.     xdev->dither_colors = NULL;
  700. #if HaveStdCMap
  701.     /* Get a standard color map if available */
  702.     if (xdev->std_cmap = x_get_std_cmap(xdev, XA_RGB_GRAY_MAP)) {
  703.         xdev->color_info.dither_gray = xdev->std_cmap->red_max +
  704.         xdev->std_cmap->green_max +
  705.         xdev->std_cmap->blue_max + 1;
  706.     } else
  707. #endif
  708.     /* Otherwise set up a gray ramp of our own */
  709.     /* The gray ramp is limited to about 1/2 of the available */
  710.     /* colormap, the user specified maxGrayRamp (usually 128), */
  711.     /* or the number of representable grays */
  712.     {
  713.         int avail_colors = xdev->vinfo->colormap_size;
  714.  
  715.         while (!xdev->dither_colors && avail_colors) {
  716.         int ramp_size = min(avail_colors / 2,
  717.                     min(xdev->maxGrayRamp, num_rgb));
  718.         int max_gray = ramp_size - 1;
  719.         int i;
  720.  
  721.         if (ramp_size < 2) {
  722.             avail_colors = 0;
  723.             goto no_ramp;
  724.         }
  725.         xdev->color_info.dither_gray = ramp_size;
  726.         xdev->dither_colors =
  727.             (x_pixel *) gs_malloc(sizeof(x_pixel), ramp_size,
  728.                       "gdev_x_gray_ramp");
  729.         for (i = 0; i < ramp_size; i++) {
  730.             XColor xc;
  731.  
  732.             xc.red = xc.green = xc.blue =
  733.             (0xffff * i / max_gray) & xdev->color_mask;
  734.             if (i == 0) {
  735.             xdev->dither_colors[i] = xdev->foreground;
  736.             } else if (i == max_gray) {
  737.             xdev->dither_colors[i] = xdev->background;
  738.             } else {
  739.             if (XAllocColor(xdev->dpy, xdev->cmap, &xc)) {
  740.                 xdev->dither_colors[i] = xc.pixel;
  741.             } else {
  742.                 avail_colors = i - 1;
  743.                 for (i = 1; i <= avail_colors; i++) {
  744.                 XFreeColors(xdev->dpy, xdev->cmap,
  745.                         &(xdev->dither_colors[i]), 1, 0);
  746.                 }
  747.                 gs_free((char *)xdev->dither_colors,
  748.                     sizeof(x_pixel), ramp_size,
  749.                     "gdev_x_gray_ramp");
  750.                 xdev->dither_colors = NULL;
  751.                 goto no_ramp;
  752.             }
  753.             }
  754.         }
  755. no_ramp:    ;
  756.         }
  757.         if (!xdev->dither_colors) {
  758.         goto monochrome;
  759.         }
  760.     }
  761.  
  762.     /* Allocate space for dynamic colors, do at most 256 */
  763.     /* If there are more avaiaible, we ask the X server */
  764.     xdev->dynamic_number = 0;
  765.     xdev->dynamic_size = min(256, xdev->vinfo->colormap_size);
  766.     xdev->dynamic_size -= xdev->color_info.dither_gray;
  767.     if (xdev->dynamic_size) {
  768.         xdev->dynamic_colors =
  769.         (XColor *) gs_malloc(sizeof(XColor), xdev->dynamic_size,
  770.                      "gdev_x_dynamic_colors");
  771.     } else {
  772.         xdev->dynamic_colors = NULL;
  773.     }
  774.     } else if (palette == 'M') {
  775. monochrome:
  776.     xdev->color_info.num_components = 1;
  777.     xdev->color_info.max_gray = 1;
  778.     xdev->color_info.dither_gray = 2;
  779.     } else {
  780.     eprintf1("gs: Unknown palette: %s\n", xdev->palette);
  781.     exit(1);
  782.     }
  783. }
  784.  
  785. /* Setup X11 font mapping. */
  786. private char *
  787. get_ps_name(char **cpp, int *len)
  788. {
  789.     char *ret;
  790.     *len = 0;
  791.     /* skip over whitespace and newlines */
  792.     while (**cpp == ' ' || **cpp == '\t' || **cpp == '\n') {
  793.     (*cpp)++;
  794.     }
  795.     /* return font name up to ":", whitespace, or end of string */
  796.     if (**cpp == ':' || **cpp == '\0') {
  797.     return NULL;
  798.     }
  799.     ret = *cpp;
  800.     while (**cpp != ':' &&
  801.        **cpp != ' ' && **cpp != '\t' && **cpp != '\n' &&
  802.        **cpp != '\0') {
  803.     (*cpp)++;
  804.     (*len)++;
  805.     }
  806.     return ret;
  807. }
  808.  
  809. private char *
  810. get_x11_name(char **cpp, int *len)
  811. {
  812.     char *ret;
  813.     int dashes = 0;
  814.     *len = 0;
  815.     /* skip over whitespace and the colon */
  816.     while (**cpp == ' ' || **cpp == '\t' ||
  817.        **cpp == ':') {
  818.     (*cpp)++;
  819.     }
  820.     /* return font name up to end of line or string */
  821.     if (**cpp == '\0' || **cpp == '\n') {
  822.     return NULL;
  823.     }
  824.     ret = *cpp;
  825.     while (dashes != 7 &&
  826.        **cpp != '\0' && **cpp != '\n') {
  827.     if (**cpp == '-') dashes++;
  828.     (*cpp)++;
  829.     (*len)++;
  830.     }
  831.     while (**cpp != '\0' && **cpp != '\n') {
  832.     (*cpp)++;
  833.     }
  834.     if (dashes != 7) return NULL;
  835.     return ret;
  836. }
  837.  
  838. private void
  839. gdev_x_setup_fontmap(gx_device_X *xdev)
  840. {
  841.     char *ps_name;
  842.     char *x11_name;
  843.     int ps_name_len;
  844.     int x11_name_len;
  845.     x11fontmap *font;
  846.     char *cp;
  847.  
  848.     if (!xdev->useXFonts) return;    /* If no external fonts, don't bother */
  849.  
  850.     cp = xdev->regularFonts;
  851.     while (ps_name = get_ps_name(&cp, &ps_name_len)) {
  852.     if (x11_name = get_x11_name(&cp, &x11_name_len)) {
  853.         font = (x11fontmap *)gs_malloc(sizeof(x11fontmap), 1,
  854.                        "gdev_x_setup_fontmap");
  855.         font->ps_name = (char *)gs_malloc(sizeof(char), ps_name_len+1,
  856.                           "gdev_x_setup_fontmap");
  857.         strncpy(font->ps_name, ps_name, ps_name_len);
  858.         font->ps_name[ps_name_len] = '\0';
  859.         font->x11_name = (char *)gs_malloc(sizeof(char), x11_name_len,
  860.                            "gdev_x_setup_fontmap");
  861.         strncpy(font->x11_name, x11_name, x11_name_len-1);
  862.         font->x11_name[x11_name_len-1] = '\0';
  863.         font->std_names = NULL;
  864.         font->iso_names = NULL;
  865.         font->std_count = -1;
  866.         font->iso_count = -1;
  867.         font->next = xdev->regular_fonts;
  868.         xdev->regular_fonts = font;
  869.     }
  870.     }
  871.  
  872.     cp = xdev->symbolFonts;
  873.     while (ps_name = get_ps_name(&cp, &ps_name_len)) {
  874.     if (x11_name = get_x11_name(&cp, &x11_name_len)) {
  875.         font = (x11fontmap *)gs_malloc(sizeof(x11fontmap), 1,
  876.                        "gdev_x_setup_fontmap");
  877.         font->ps_name = (char *)gs_malloc(sizeof(char), ps_name_len+1,
  878.                           "gdev_x_setup_fontmap");
  879.         strncpy(font->ps_name, ps_name, ps_name_len);
  880.         font->ps_name[ps_name_len] = '\0';
  881.         font->x11_name = (char *)gs_malloc(sizeof(char), x11_name_len,
  882.                            "gdev_x_setup_fontmap");
  883.         strncpy(font->x11_name, x11_name, x11_name_len-1);
  884.         font->x11_name[x11_name_len-1] = '\0';
  885.         font->std_names = NULL;
  886.         font->iso_names = NULL;
  887.         font->std_count = -1;
  888.         font->iso_count = -1;
  889.         font->next = xdev->symbol_fonts;
  890.         xdev->symbol_fonts = font;
  891.     }
  892.     }
  893.  
  894.     cp = xdev->dingbatFonts;
  895.     while (ps_name = get_ps_name(&cp, &ps_name_len)) {
  896.     if (x11_name = get_x11_name(&cp, &x11_name_len)) {
  897.         font = (x11fontmap *)gs_malloc(sizeof(x11fontmap), 1,
  898.                        "gdev_x_setup_fontmap");
  899.         font->ps_name = (char *)gs_malloc(sizeof(char), ps_name_len+1,
  900.                           "gdev_x_setup_fontmap");
  901.         strncpy(font->ps_name, ps_name, ps_name_len);
  902.         font->ps_name[ps_name_len] = '\0';
  903.         font->x11_name = (char *)gs_malloc(sizeof(char), x11_name_len,
  904.                            "gdev_x_setup_fontmap");
  905.         strncpy(font->x11_name, x11_name, x11_name_len-1);
  906.         font->x11_name[x11_name_len-1] = '\0';
  907.         font->std_names = NULL;
  908.         font->iso_names = NULL;
  909.         font->std_count = -1;
  910.         font->iso_count = -1;
  911.         font->next = xdev->dingbat_fonts;
  912.         xdev->dingbat_fonts = font;
  913.     }
  914.     }
  915. }
  916.